package simulator;

import java.util.concurrent.PriorityBlockingQueue;

import simulator.queue.Event;
import simulator.queue.Item;
import simulator.queue.ItemComparator;
import simulator.util.ExponentialNumberGenerator;


public class Server 
{
	public static final int STATE_IDLE = 0;
	public static final int STATE_BUSY_SERVING_ITEM_TYPE_1 = 1;
	public static final int STATE_BUSY_SERVING_ITEM_TYPE_2 = 2;
	
	private final PriorityBlockingQueue<Item> itemQueue1 = new PriorityBlockingQueue<Item>(100, new ItemComparator());
	private final PriorityBlockingQueue<Item> itemQueue2 = new PriorityBlockingQueue<Item>(100, new ItemComparator());
	
	private final int id;
	private final double currentTime = 0;
	private int currentState;
	private Item itemInService;
	private final System system;
	
	public Server(int id, System system) 
	{
		this.id = id;
		this.currentState = STATE_IDLE;
		this.system = system;
	}

	public int getCurrentState() {
		return currentState;
	}

	public void setCurrentState(int currentState) {
		this.currentState = currentState;
	}

	public int getId() {
		return id;
	}

	public Item getItemInService() {
		return itemInService;
	}

	public void setItemInService(Item itemInService) {
		this.itemInService = itemInService;
	}

	public double getCurrentTime() {
		return currentTime;
	}

	public boolean addItemOnQueue1(Item item)
	{
		return itemQueue1.add(item);
	}
	
	public boolean addItemOnQueue2(Item item)
	{
		return itemQueue2.add(item);
	}
	
	public Item peekItemOnQueue1()
	{
		return itemQueue1.peek();
	}
	
	public Item peekItemOnQueue2()
	{
		return itemQueue2.peek();
	}
	
	public Event processNextItem()
	{
		// if the server is Idle
		if(currentState == STATE_IDLE)
		{
			// and the queue 1 is empty
			if(itemQueue1.isEmpty()) 
			{
				//TODO: Is possible only see and not remove the item on queue2?
				if (!itemQueue2.isEmpty())
				{
					itemInService = itemQueue2.remove();
					itemInService.setLastTimeInService(currentTime);
					currentState = STATE_BUSY_SERVING_ITEM_TYPE_2;
//					system.addEventExitServerEvent(currentTime+ExponentialNumberGenerator.generate(randon, rate), item);
				}
			} 
			else
			{
				itemInService = itemQueue1.remove();
				itemInService.setLastTimeInService(currentTime);
				currentState = STATE_BUSY_SERVING_ITEM_TYPE_1;
			}
		}
		if(currentState == STATE_BUSY_SERVING_ITEM_TYPE_2)
		{
			if(itemQueue1.isEmpty()) 
			{
				double lastServedTime = itemInService.getLastTimeInService() - currentTime;
				itemInService.setServedTime(itemInService.getServedTime() + lastServedTime);
			} 
		}
			
		return null;
	}
}